﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Model;
using Model.Entities;
using MusicSite.ViewClasses;

namespace MusicSite.Views.Content.Track
{
    public partial class EditTrack : BasePage
    {
        private TrackProvider trProv = new TrackProvider();
        private TrackDetails editTrack = new TrackDetails();
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckAuthenticationEditPage();
            string trackId = Request.QueryString["TrackId"];
            if (string.IsNullOrEmpty(trackId))
            {
                btnDelete.Visible = false;
                btnUpdate.Text = "Create";
                FillDropDownList();
                return;
            }
            editTrack = trProv.GetTrackById(Convert.ToInt32(trackId));
            if (!IsPostBack)
            {
                trackName.Text = editTrack.TrackName;
                rating.Value = Convert.ToString(editTrack.Rating);
                FillDropDownList();
                album.SelectedValue = editTrack.AlbumId.ToString();
                timeTrack.Text = editTrack.TimeTrack.Value.ToString("mm:ss");
            }
        }

        protected void UpdateTrack(object sender, EventArgs e)
        {
            if (IsValid)
            {
                editTrack.TrackName = trackName.Text;
                editTrack.Rating = Convert.ToInt32(rating.Value);
                editTrack.TimeTrack = DateTime.Parse(timeTrack.Text);
                editTrack.AlbumId = Convert.ToInt32(album.SelectedValue);
                if (btnUpdate.Text == "Create")
                    trProv.InsertTrack(editTrack);
                else
                    trProv.UpdateTrack(editTrack);
                Response.Redirect("~/Views/Content/Track/IndexTrack.aspx");
            }
        }

        protected void FillDropDownList()
        {
            album.DataSource = new AlbumProvider().GetAlbums();
            album.DataTextField = "AlbumName";
            album.DataValueField = "AlbumId";
            album.DataBind();
        }

        protected void DeleteTrack(object sender, EventArgs e)
        {
            trProv.DeleteTrack(editTrack);
            Response.Redirect("~/Views/Content/Track/IndexTrack.aspx");
        }

        public void SaveImageOnDisc(FileUpload img)
        {
            if (string.IsNullOrEmpty(img.FileName) || img.FileBytes.Length == 0)
                return;
            string dir = Server.MapPath("~/Content/images/" + img.FileName);
            img.SaveAs(dir);
        }
    }
}
